﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;

namespace Liquid.Windows {
	public sealed class WindowStateMonitor : Component, ISupportInitialize {
		protected override bool CanRaiseEvents { get { return true; } }

		WeakReference<Form> m_Form;
		FormWindowState state;

		public void BeginInit() { }

		public void EndInit() {
			var form = this.Form;
			if (form != null) {
				form.Layout += Form_Layout;
				state = form.WindowState;
			}
		}

		public Form Form {
			get {
				if (m_Form == null)
					return null;
				return m_Form.Target;
			}
			set { m_Form = new WeakReference<Form>(value); }
		}

		void Form_Layout(object sender, LayoutEventArgs e) {
			var form = (Form)sender;
			if (form.WindowState != state) {
				var oldState = state;
				state = form.WindowState;
				switch (form.WindowState) {
					case FormWindowState.Maximized:
						if (Maximized != null)
							Maximized(this, EventArgs.Empty);
						if (oldState == FormWindowState.Minimized && Restored != null)
							Restored(this, EventArgs.Empty);
						break;
					case FormWindowState.Minimized:
						if (Minimized != null)
							Minimized(this, EventArgs.Empty);
						break;
					case FormWindowState.Normal:
						if (Normalized != null)
							Normalized(this, EventArgs.Empty);
						if (oldState == FormWindowState.Minimized && Restored != null)
							Restored(this, EventArgs.Empty);
						break;
				}
			}
		}

		public event EventHandler Maximized;
		public event EventHandler Minimized;
		public event EventHandler Normalized;
		public event EventHandler Restored;
	}
}
